// pages/property-repair/property-repair.js
import api from "../../utils/request"
Page({
  data: {
    activeTab: "all",
    searchValue: "",
    currentUserId: "1003", // 当前登录用户ID，实际应从登录信息获取
    repairs: [
      {
        id: 2,
        repairNumber: "1001",
        repairTime: "2025-06-05",
        houseId: 62,
        houseAddress: "城市花园1栋1单元1层101",
        repairArea: "客厅",
        repairTypeId: 1,
        repairTypeName: "水电维修",
        problemDescription: "天花板漏水，需要紧急处理",
        status: 2,
        statusText: "已完成",
        statusType: "success",
        staffId: 1007,
        staffName: "王师傅",
        lastAcceptTime: "2025-06-18",
        priority: "normal",
        canAccept: false,
        isAccepted: false,
      },
      {
        id: 3,
        repairNumber: "WR1749656132502",
        repairTime: "2025-06-04",
        houseId: 117,
        houseAddress: "城市花园2栋2单元3层302",
        repairArea: "卧室",
        repairTypeId: 1,
        repairTypeName: "家电维修",
        problemDescription: "卧室空调制冷失效，室内温度过高",
        status: 1,
        statusText: "待接单",
        statusType: "primary",
        staffId: 1003,
        staffName: "李师傅",
        lastAcceptTime: null,
        priority: "urgent",
        canAccept: true, // 当前用户是负责人，可以接单
        isAccepted: false,
      },
      {
        id: 4,
        repairNumber: "WR1749656479114",
        repairTime: "2025-06-11",
        houseId: 102,
        houseAddress: "城市花园3栋1单元2层201",
        repairArea: "厨房",
        repairTypeId: 1,
        repairTypeName: "管道维修",
        problemDescription: "水管漏水，影响正常使用",
        status: 1,
        statusText: "待接单",
        statusType: "primary",
        staffId: 1004,
        staffName: "张师傅",
        lastAcceptTime: null,
        priority: "normal",
        canAccept: false, // 当前用户不是负责人，不能接单
        isAccepted: false,
      },
      {
        id: 5,
        repairNumber: "WR1749657312825",
        repairTime: "2025-06-11",
        houseId: 68,
        houseAddress: "城市花园4栋3单元1层101",
        repairArea: "厨房",
        repairTypeId: 1,
        repairTypeName: "其他维修",
        problemDescription: "厨房设施需要检修维护",
        status: 0,
        statusText: "待派单",
        statusType: "warning",
        staffId: null,
        staffName: "",
        lastAcceptTime: null,
        priority: "normal",
        canAccept: false,
        isAccepted: false,
      },
    ],
    allRepairs: [],
    statistics: {
      total: 0,
      pending: 0,
      assigned: 0,
      completed: 0,
    },
  },

  onLoad() {
    const user= wx.getStorageSync('userInfo')
    this.setData({
      allRepairs: this.data.repairs,
    })
    console.log(user)
    this.calculateStatistics()
    this.loadRepairs()
  },

  onShow(){
    this.setData({
      allRepairs: this.data.repairs,
    })
    console.log(user)
    this.calculateStatistics()
    this.loadRepairs()
  },

  // 加载维修工单数据
  loadRepairs() {
    wx.showLoading({
      title: "加载中...",
    })
    // 模拟API请求
    setTimeout(async() => {
      // 实际项目中这里应该是API请求
      const result = await api.get("/property/repairRequest/myOrder")
      this.setData({
        repairs: result.data,
        allRepairs: result.data
      })
      this.calculateStatistics()

      wx.hideLoading()
    }, 500)
  },

  // 计算统计数据
  calculateStatistics() {
    const { allRepairs } = this.data
    const statistics = {
      total: allRepairs.length,
      pending: allRepairs.filter((item) => item.status === 0).length,
      assigned: allRepairs.filter((item) => item.status === 1).length,
      completed: allRepairs.filter((item) => item.status === 2).length,
    }

    this.setData({ statistics })
  },

  // 标签页切换
  onTabChange(e) {
    const { name } = e.detail
    this.setData({ activeTab: name })
    this.filterRepairs(name)
  },

  // 筛选工单
  filterRepairs(status) {
    const { allRepairs, searchValue } = this.data
    let filteredRepairs = allRepairs

    // 按状态筛选
    if (status !== "all") {
      filteredRepairs = filteredRepairs.filter((item) => item.status.toString() === status)
    }

    // 按搜索关键词筛选
    if (searchValue.trim()) {
      filteredRepairs = filteredRepairs.filter(
        (item) =>
          item.repairNumber.toLowerCase().includes(searchValue.toLowerCase()) ||
          item.houseAddress.toLowerCase().includes(searchValue.toLowerCase()),
      )
    }

    this.setData({
      repairs: filteredRepairs,
    })
  },

  // 搜索变化
  onSearchChange(e) {
    this.setData({
      searchValue: e.detail,
    })
  },

  // 执行搜索
  onSearch() {
    this.filterRepairs(this.data.activeTab)
  },

  // 点击工单项
  onItemClick(e) {
    const { id } = e.currentTarget.dataset

    console.log("------",e.currentTarget.dataset)
    wx.navigateTo({
      url: `/pages/repair_detail/repair_detail?id=${id}`,
    })
  },

  // 接单
  onAcceptOrder(e) {
    const { id, repairNumber } = e.currentTarget.dataset

    wx.showModal({
      title: "确认接单",
      content: `确定要接受工单 ${repairNumber} 吗？`,
      success: (res) => {
        if (res.confirm) {
          this.handleAcceptOrder(id)
        }
      },
    })
  },

  // 处理接单
  handleAcceptOrder(id) {
    wx.showLoading({
      title: "接单中...",
    })

    // 模拟API请求
    setTimeout(async() => {
      // 实际项目中这里应该是API请求
      await api.put(`/property/repairRequest/accept/${id}`)

      // 更新本地数据
      // const { repairs, allRepairs } = this.data
      // const updateData = (list) =>
      //   list.map((item) => {
      //     if (item.id === id) {
      //       return {
      //         ...item,
      //         lastAcceptTime: new Date().toISOString().split("T")[0],
      //         isAccepted: true,
      //         canAccept: false,
      //       }
      //     }
      //     return item
      //   })

      // this.setData({
      //   repairs: updateData(repairs),
      //   allRepairs: updateData(allRepairs),
      // })

      wx.hideLoading()
      wx.showToast({
        title: "接单成功",
        icon: "success",
      })
      const user= wx.getStorageSync('userInfo')
      this.setData({
        allRepairs: this.data.repairs,
      })
      console.log(user)
      this.calculateStatistics()
      this.loadRepairs()
    }, 1000)
  },

  // 完成工单
  onCompleteOrder(e) {
    e.stopPropagation() // 阻止事件冒泡
    const { id, repairNumber } = e.currentTarget.dataset

    wx.showModal({
      title: "确认完成",
      content: `确定要完成工单 ${repairNumber} 吗？`,
      success: (res) => {
        if (res.confirm) {
          this.handleCompleteOrder(id)
        }
      },
    })
  },

  // 处理完成工单
  handleCompleteOrder(id) {
    wx.showLoading({
      title: "处理中...",
    })

    // 模拟API请求
    setTimeout(() => {
      // 实际项目中这里应该是API请求
      // await api.completeRepairOrder(id)

      // 更新本地数据
      const { repairs, allRepairs } = this.data
      const updateData = (list) =>
        list.map((item) => {
          if (item.id === id) {
            return {
              ...item,
              status: 2,
              statusText: "已完成",
              statusType: "success",
            }
          }
          return item
        })

      this.setData({
        repairs: updateData(repairs),
        allRepairs: updateData(allRepairs),
      })

      this.calculateStatistics()

      wx.hideLoading()
      wx.showToast({
        title: "工单已完成",
        icon: "success",
      })
    }, 1000)
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadRepairs()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1500)
  },
})
